//
//  StoreCategoryViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/7/6.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "HZLocation.h"

#import "StoreCategoryListCell.h"

#import "StoreCategoryTableHeader.h"

#import "ServiceCatSubSegNaviView.h"

#import "StoreCategorySubSegViewController.h"
#import "StoreDetailViewController.h"
#import "StoreHotelDetailViewController.h"
#import "SearchViewController.h"
#import "MessageCenterViewController.h"
#import "StoreCategoryViewController.h"

@interface StoreCategoryViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, HZLocationDelegate>

@property (nonatomic, strong) HZLocation *locationManager;


@property (nonatomic, strong)UITableView *tableview;

@property (nonatomic, strong) ServiceCatSubSegNaviView *naviView;

@property (nonatomic, strong) StoreCategoryTableHeader *storeCatTableHeader;

//头部分类的数据
@property (nonatomic, strong) NSMutableArray <ProClassificationModel *>*classificationDataArray;

@property (nonatomic, strong) NSMutableArray <CommonSellerModule *>*dataArray;

@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, assign) NSInteger currentId;

@property (nonatomic, strong) UIView *sectionHeadView;

@end

@implementation StoreCategoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    [self locationManager];
}
- (void)initView {
    self.title = IsStrNotEmpty(self.className) ? self.className : @"商家列表";
    self.view.backgroundColor = UIColor.whiteColor;
    if (self.classId > 0) {
        [self.view addSubview:self.tableview];
        [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(0);
        }];
    } else {
        self.navigationController.navigationBarHidden = YES;
        #if RT_INTERACTIVE_PUSH
            self.rt_navigationController.rt_enableInteractivePush = YES;
        #endif
        self.rt_disableInteractivePop = NO;
        [RACObserve([TT_MessageManager manager], totalUnReadCount) subscribeNext:^(id x) {
            if ([TT_MessageManager manager].totalUnReadCount > 0) {
                self.naviView.msgBtn.badgeValue = [NSString stringWithFormat:@"%d",[TT_MessageManager manager].totalUnReadCount];
                self.naviView.msgBtn.badgeBGColor = [UIColor redColor];
            } else {
                self.naviView.msgBtn.badgeValue = @"";
                self.naviView.msgBtn.badgeBGColor = [UIColor clearColor];
            }
        }];
        [self.view addSubview:self.naviView];
        [self.naviView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.top.mas_equalTo(kStatusBarHeight);
            make.height.mas_equalTo(NavBar_Height);
        }];
        [self.view addSubview:self.tableview];
        [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.mas_equalTo(0);
            make.top.mas_equalTo(self.naviView.mas_bottom);
        }];
    }
    [self.tableview reloadData];
    [self initViewAction];
}
- (void)initViewAction {
    if (self.classId > 0) {
        return;
    }
    WEAKSELF
    self.storeCatTableHeader.BA_StoreCategoryCellBlock = ^(NSInteger index) {
        [weakSelf refreshParam];
        weakSelf.currentId = weakSelf.classificationDataArray[index].scId;
        [weakSelf request_storeWithId:weakSelf.classificationDataArray[index].scId];
    };
    self.naviView.ServiceCatSubSegNaviBlock = ^(ServiceCatNaviType type) {
        switch (type) {
            case ServiceCatNaviType_back:{
                
            } break;
            case ServiceCatNaviType_im:{
                MessageCenterViewController *vc = [[MessageCenterViewController alloc] init];
                [weakSelf.navigationController pushViewController:vc animated:YES];
                
            } break;
            default:
                break;
        }
    };
}
- (void)bindTableViewHeaderView {
    if (self.classId > 0) {
        return;
    }
    self.storeCatTableHeader = [[StoreCategoryTableHeader alloc]initWithFrame:CGRectMake(0, 0, TTScreenWidth, [StoreCategoryTableHeader calculateHeight:self.classificationDataArray.count])];
    [self.storeCatTableHeader fillHeadWithArray:self.classificationDataArray];
    self.tableview.tableHeaderView = self.storeCatTableHeader;
    self.storeCatTableHeader.autoresizingMask = UIViewAutoresizingNone;
    [self initViewAction];
}
#pragma mark - request
- (void)refreshParam {
    self.pageSize = 20;
    self.pageNum = 1;
    [self.tableview.mj_header endRefreshing];
    [self.tableview.mj_footer endRefreshing];
    [self.tableview.mj_footer resetNoMoreData];
}
- (void)request_catList {
    if (self.classId > 0) {
        [self refreshParam];
        self.currentId = self.classId;
        [self request_storeWithId:self.classId];
    } else {
        NSMutableDictionary *dic = @{}.mutableCopy;
        [dic setValue:@(-1) forKey:@"parentId"];
        [dic setValue:@"1" forKey:@"scType"];
        NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_Category];
        
        WEAKSELF
        [SVProgressHUD showWithStatus:@"正在加载"];
        [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
            [SVProgressHUD dismiss];
            if ([data isKindOfClass:[NSDictionary class]]) {
                //请求成功
                NSInteger code = [[data valueForKey:@"code"] integerValue];
                if (code == 10000) {
                    NSDictionary *resultDic = [data valueForKey:@"data"];
                    if (![resultDic isKindOfClass:[NSDictionary class]]) {
                        return;
                    }
                    NSArray *oneList = [resultDic valueForKey:@"sysClassificationList"];
                    if ([oneList isKindOfClass:[NSArray class]]) {
                        
                        weakSelf.classificationDataArray = @[].mutableCopy;
                        for (int i = 0; i < oneList.count; i++) {
                            ProClassificationModel *oneModel = [ProClassificationModel modelWithDictionary:oneList[i]];
                            if (i==0) {
                                [weakSelf refreshParam];
                                weakSelf.currentId = oneModel.scId;
                                [weakSelf request_storeWithId:oneModel.scId];
                            }
                            [weakSelf.classificationDataArray addObject:oneModel];
                        }
                        [weakSelf bindTableViewHeaderView];
                    }
                }
            }
        } FailedBlock:^(NSError * _Nonnull error) {
            [SVProgressHUD dismiss];
        }];
    }
}

- (void)request_storeWithId:(NSInteger)catId {
    
    NSString *classId = [NSString stringWithFormat:@"%ld",(long)catId];
    [[StatisticManager shareManager] uploadClassCategory:classId];
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:@(self.pageNum) forKey:@"pageNum"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];
    
    NSMutableDictionary *t = @{}.mutableCopy;
    [t setValue:@(catId) forKey:@"classId"];
    [t setValue:[TTUserModel sharedObject].cityId forKey:@"sellerCityId"];

    [dic setValue:t forKey:@"t"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_StoreCategory];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [SVProgressHUD dismiss];
        [weakSelf.tableview.mj_footer endRefreshing];
        [weakSelf.tableview.mj_header endRefreshing];
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            BOOL hasNextPage = [[data valueForKey:@"hasNextPage"] boolValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if (![resultDic isKindOfClass:[NSDictionary class]]) {
                    return;
                }
                NSArray *list = [resultDic valueForKey:@"list"];
                
                if (weakSelf.pageNum == 1) {
                    weakSelf.dataArray = @[].mutableCopy;
                }
                
                if ([list isKindOfClass:[NSArray class]]) {
                    
                    for (int i = 0; i < list.count; i++) {
                        NSDictionary *listDic = list[i];
                        if ([listDic isKindOfClass:[NSDictionary class]]) {
                            CommonSellerModule *model = [CommonSellerModule modelWithDictionary:list[i]];

                            NSDictionary *sellerQualityAuthentication = [listDic valueForKey:@"sellerQualityAuthentication"];
                            model.sellerQualityAuthentication = [CommonQualityTagModel modelWithDictionary:sellerQualityAuthentication];
                            
                            if (model.lat > 0 && model.lng > 0) {
                                model.distance = [Utilities calculateStart:CLLocationCoordinate2DMake([TTUserModel sharedObject].latitude, [TTUserModel sharedObject].longitude) end:CLLocationCoordinate2DMake(model.lat,model.lng)];
                            }
                            
                            NSArray *coverPaths = [listDic valueForKey:@"coverPaths"];
                            
                            if ([coverPaths isKindOfClass:[NSArray class]]) {
                                model.coverPaths = @[].mutableCopy;
                                for (int j = 0; j < coverPaths.count; j++) {
                                    NSDictionary *coverPathsDic = coverPaths[j];
                                    CommonImageModel *imgModel = [CommonImageModel modelWithDictionary:coverPathsDic];
                                    [model.coverPaths addObject:imgModel];
                                }
                            }
                            [weakSelf.dataArray addObject:model];
                        }
                    }
                    [weakSelf.tableview reloadData];
                    if (hasNextPage) {
                        [weakSelf.tableview.mj_footer resetNoMoreData];
                    } else {
                        [weakSelf.tableview.mj_footer endRefreshingWithNoMoreData];
                    }
                }
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
    }];
    
}
#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    NSLog(@"heightForHeaderInSection: %lf", CGFLOAT_MIN);
    if (self.classId > 0) {
        return CGFLOAT_MIN;
    } else {
        return 10;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    //return CGFLOAT_MIN;
    return 0;
}

#pragma mark sectionheader
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return self.sectionHeadView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [StoreCategoryListCell calculateHeightWithModel:self.dataArray[indexPath.row]];;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if ([self.dataArray[indexPath.row].classId isEqualToString:Store_Category_Hotel]) {
        
        StoreHotelDetailViewController *vc = [[StoreHotelDetailViewController alloc] init];
        vc.storeId = self.dataArray[indexPath.row].sellerId;
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        StoreDetailViewController *vc = [[StoreDetailViewController alloc] init];
        vc.storeId = self.dataArray[indexPath.row].sellerId;
        [self.navigationController pushViewController:vc animated:YES];
    }

}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    StoreCategoryListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"StoreCategoryListCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    [cell fillCellWithModel:self.dataArray[indexPath.row]];
    return cell;
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    SearchViewController *vc = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    return NO;
}
#pragma mark - HZLocationDelegate

//定位成功
- (void)currentLocation:(NSDictionary *)locationDictionary coordinate:(CLLocationCoordinate2D)coordinate {

    [[TTUserModel sharedObject].userModelDefault setDouble:coordinate.latitude forKey:@"TT_latitude"];
    [[TTUserModel sharedObject].userModelDefault setDouble:coordinate.longitude forKey:@"TT_longitude"];
    
    [self request_catList];
}

/// 拒绝定位
- (void)refuseToUsePositioningSystem:(NSString *)message {
    NSLog(@"%@",message);
    [self request_catList];
}

/// 定位失败
- (void)locateFailure:(NSString *)message {
    NSLog(@"%@",message);
    [self request_catList];
}
#pragma mark - click
- (void)goBack {
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - lazy
- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor = UIColor.whiteColor;

        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerNib:[UINib nibWithNibName:@"StoreCategoryListCell" bundle:nil] forCellReuseIdentifier:@"StoreCategoryListCellID"];
        
        WEAKSELF
        _tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf refreshParam];
            [weakSelf request_storeWithId:weakSelf.currentId];
        }];
        _tableview.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            weakSelf.pageNum ++;
            [weakSelf request_storeWithId:weakSelf.currentId];
        }];
        _tableview.mj_footer.ignoredScrollViewContentInsetBottom = Is_IPhoneX ? Bottom_SafeHeight : CGFLOAT_MIN;
        
        if (@available(iOS 11.0, *)) {
            _tableview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableview.estimatedRowHeight = 0;
            _tableview.estimatedSectionFooterHeight = 0;
            _tableview.estimatedSectionHeaderHeight = 0;
        }
        if (@available(ios 15.0,*)) {
            UITableView.appearance.sectionHeaderTopPadding = 0;
        }
        _tableview.tableHeaderView = [UIView new];
        _tableview.tableFooterView = [UIView new];
    }
    return _tableview;
}

- (UIView *)sectionHeadView {
    if (!_sectionHeadView) {
        _sectionHeadView = [[UIView alloc] init];
        _sectionHeadView.backgroundColor = UIColorHex(0xf1f1f1);
    }
    return _sectionHeadView;
}

- (ServiceCatSubSegNaviView *)naviView {
    if (!_naviView) {
        _naviView = [[NSBundle mainBundle] loadNibNamed:@"ServiceCatSubSegNaviView"owner:nil options:nil].firstObject;
        [_naviView.backBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
        _naviView.searchTF.delegate = self;

    }
    return _naviView;
}

- (NSMutableArray<ProClassificationModel *> *)classificationDataArray {
    if (!_classificationDataArray) {
        _classificationDataArray = @[].mutableCopy;
    }
    return _classificationDataArray;
}

- (NSMutableArray<CommonSellerModule *> *)dataArray {
    if (!_dataArray) {
        _dataArray = @[].mutableCopy;
    }
    return _dataArray;
}

- (HZLocation *)locationManager {
    if (!_locationManager) {
        _locationManager = [[HZLocation alloc] init];
        _locationManager.delegate = self;
    }
    return _locationManager;
}
@end
